/*!
 * \file cicsts_header.c
 *
 * \brief 消息头操作
 *
 * All Rights Reserved Copyright (C) 2014 broada,Co.,Ltd.
 *
 * \version 1.0
 * \author songbb
 * \date 2016/04/22
 *
 */

#include <stdio.h>
#include <netinet/in.h>
#include <frct_comm.h>

#include "cicsts_comm.h"
#include "cicsts_core.h"
#include "cicsts_header.h"

int cicsts_header_unpack(int i_is_request
                        , char *p_payload
                        , unsigned int ui_payload_len
                        , CicsTS_header *p_st_cicsts_header)
{
    unsigned int *p_ui_pkt_len;
    unsigned int *p_ui_msg_id;
    unsigned short *p_us_tmp;
    unsigned short us_tmp;
    char c_tmp;

    if ((i_is_request == FR_YES && ui_payload_len < APM_CICSTS_PKT_REQ_HEADER_LEN) ||
        (i_is_request == FR_NO && ui_payload_len < APM_CICSTS_PKT_RESP_HEADER_LEN))
        goto error;

    p_ui_pkt_len = (unsigned int *) p_payload;
    p_st_cicsts_header->ui_pkt_len = (unsigned int) ntohl(*p_ui_pkt_len);

    p_ui_msg_id = (unsigned int *)(p_payload + 4);
    p_st_cicsts_header->ui_msg_id = (unsigned int) ntohl(*p_ui_msg_id);

    if (i_is_request == FR_YES)
    {
        p_us_tmp = (unsigned short *)(p_payload + 72);
        us_tmp = ntohs(*p_us_tmp);
        if (us_tmp == 0xe100)
            p_st_cicsts_header->ui_header_len = APM_CICSTS_PKT_REQ_HEADER_LEN + 17;
        else
        {
            c_tmp = *(p_payload + 80);
            p_st_cicsts_header->ui_header_len = APM_CICSTS_PKT_REQ_HEADER_LEN + (unsigned int) c_tmp;
        }
    }
    else
        p_st_cicsts_header->ui_header_len = APM_CICSTS_PKT_RESP_HEADER_LEN;

    return FR_SUCC;
error:
    return FR_FAIL;
}
